package com.kingsoft.demo.xml.dom4j;

import org.dom4j.Attribute;
import org.dom4j.CDATA;
import org.dom4j.Comment;
import org.dom4j.Document;
import org.dom4j.DocumentType;
import org.dom4j.Element;
import org.dom4j.Entity;
import org.dom4j.Namespace;
import org.dom4j.ProcessingInstruction;
import org.dom4j.Text;
import org.dom4j.Visitor;
import org.dom4j.VisitorSupport;
import org.dom4j.io.SAXReader;

public class TestReader3 {

	/**
	    * 使用vistor接口
	    * @throws Exception
	    */
		public void readXml() throws Exception{
			
			
			SAXReader sr=new SAXReader();
			
			
			Document  doc=sr.read("src/emp.xml");
			
			doc.accept(new Visitor(){

				public void visit(Document arg0) {
					// TODO Auto-generated method stub
					
				}

				public void visit(DocumentType arg0) {
					// TODO Auto-generated method stub
					
				}
				
				/**
				 * 该方法将会被调用多次
				 * 当accept在解析xml文件的过程中，读取到Element节点时，自动调用该方法
				 */
				public void visit(Element el) {
					String name=el.getName();
					//取得ename
					if(name!=null && name.equals("ENAME"))
				      	System.out.println(el.getText());
				}

				public void visit(Attribute arg0) {
					// TODO Auto-generated method stub
					
				}

				public void visit(CDATA arg0) {
					// TODO Auto-generated method stub
					
				}

				public void visit(Comment arg0) {
					// TODO Auto-generated method stub
					
				}

				public void visit(Entity arg0) {
					// TODO Auto-generated method stub
					
				}

				public void visit(Namespace arg0) {
					// TODO Auto-generated method stub
					
				}

				public void visit(ProcessingInstruction arg0) {
					// TODO Auto-generated method stub
					
				}

				public void visit(Text arg0) {
					// TODO Auto-generated method stub
					
				}
				
			});
		
				
			
		}
		
		/**
		 * 使用 VisitorSupport类
		 * @throws Exception
		 */
	   public void readXml2() throws Exception{
			
			
			SAXReader sr=new SAXReader();
			
			
			Document  doc=sr.read("src/emp.xml");
			
			Visitor vt=new VisitorSupport(){
				
				/**
				 * 该方法将会被调用多次
				 * 当accept在解析xml文件的过程中，读取到Element节点时，自动调用该方法
				 */
				public void visit(Element el) {
					String name=el.getName();
					if(name!=null && name.equals("ENAME"))
				      	System.out.println(el.getText());
				}
			};
			doc.accept(vt);
		
				
			
		}
		public static void main(String []args){
			
			TestReader3 tr=new TestReader3();
			try{
				tr.readXml2();
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
}
